(function () {

	//获取项目合同细目其他数据 服务器分页
    var contractOtherData = {};
    contractOtherData.contractId=jQuery('#contractId').val();
    contractOtherData.type="0";
    var serverOtherTable;
    jQuery(document).ready(function () {
    	serverOtherTable = jQuery('#resultOtherTable').DataTable({
    		"serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/contract/getReplacement',
                "data": function (d) {
                    return $.extend({}, d, contractOtherData);
                }
            },
            columns: [
                {
                	data: null
                },
                {
    	            data: null,
    	            defaultContent: "",
    	            render: function (data, type, full, meta) {
    	            	var id=data.id
    	            	var operate ='<input type="checkbox" class="checkchildOther">';
    	            	return operate;
    	            }   
                },
                {
                    data: 'deviceName'
                },
                {
                    data: 'type'
                },
                {
                	data: 'material'
                },
                {
                	data: 'unit'
                },
                {
                    data: 'amount'
                },
                {
                    data: 'price'
                }
                ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
    	
    	//删除项目合同细目其他
    	jQuery('.delOtherBtn').on('click', function () {
    		   var selects=getSelect("#resultOtherTable",1);
    		   var url=window.rootPath+"/ui/contract/deleteReplacement";
    		   var contractId = jQuery("#contractId").val(); 
    		   var totalSum = jQuery("#totalSum").val();
    		   $("#checkAllOther").prop("checked", false);
    		   delSelect(selects,url,serverOtherTable);
    		   var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + contractId + '&totalSum=' + totalSum;
    		   jQuery.ajax({
               	type : 'get',
               	url : encodeURI(urlxy),
               	dataType : 'json',
               	contentType : 'application/json;charset=utf-8',
               	success : function(data) {
               		if(data==0){
               			alert("合同金额与细目的总金额相同！");
               		} else if(data==1){
               			alert("合同金额小于细目的总金额！");
               		} else if(data==2){
               			alert("合同金额大于细目的总金额！");
               		}
               	}
               });
    		});
    	
    	//其他添加按钮
		jQuery('.addOtherBtn').on("click", function() {
			var contractId = jQuery('#contractId').val();
        	if(contractId == ""){
            	if (confirm("当前合同还未保存，是否保存？")) {
            		saveContract('addOtherBtn');
            	}
            }else{
            	showReplacementModal();
            }
		});
		
		//其他编辑弹窗显示
    	jQuery('.editOtherBtn').on('click', function () {
    		var selects=getSelect("#resultOtherTable",1);
    		if(selects.length==0){
 		       $.springLemonDialog({
 		         content: '请选择需要编辑的记录',// 确认文本
 		         clickButton: function (sender, modal, index) {// 按钮事件处理
 		             $(this).closeDialog(modal);
 		         }
 		       }); 
 		    }else if (selects.length > 1) {
				$.springLemonDialog({
					content : '一次只能编辑一条记录',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
 		    }else if(selects.length==1){
 		    	var replacementId=selects[0].id;
 		    	var replacementcreateTime=selects[0].createTime;
  			    var deviceName=selects[0].deviceName;
  			    var type=selects[0].type;
  			    var material=selects[0].material;
  			    var unit=selects[0].unit;
  			    var amount=selects[0].amount;
  			    var price=selects[0].price;
  			    jQuery('#replacementId').val(replacementId);
  			    jQuery("#replacementcreateTime").val(replacementcreateTime);
	  			jQuery('#deviceName').val(deviceName);
	  			jQuery('#type').val(type);
	  			jQuery('#material').val(material);
	  			jQuery('#unit').val(unit);
	  			jQuery('#amount').val(amount);
	  			jQuery('#price').val(price);
  			    jQuery('#editReplacementModal').modal('show');
   		    }
    		
 		});
    	
    	//新建/编辑备件保存
    	jQuery('.saveOtherBtn').on('click', function () {
    			if(jQuery("#editOneReplacementAtrrForm") && !jQuery("#editOneReplacementAtrrForm").Validform({tiptype:3, showAllError:true}).check(false)){
                    return;
                };
                jQuery(".saveOtherBtn").attr("disabled", true);
                var totalSum = jQuery("#totalSum").val();
    			var replacementId = jQuery('#replacementId').val();
    			var createTime = jQuery("#replacementcreateTime").val();
    			var contractId = jQuery("#contractId").val();
    			var contractType = "项目合同";
      			var deviceName = jQuery('#deviceName').val();
      			var type = jQuery('#type').val();
      			var material = jQuery('#material').val();
      			var unit = jQuery('#unit').val();
      			var amount = jQuery('#amount').val();
      			var price = jQuery('#price').val();
      			if (replacementId == '') {
	      			var data={
	                        "contractID":contractId,
	                        "contractType":contractType,
	                        "deviceName": deviceName,
	                        "type": type,
	                        "material": material,
	                        "unit": unit,
	                        "amount": amount,
	                        "price": price
	                    };
      			} else{
      				var data={
	                        "id":replacementId,
	                        "createTime" : createTime,
	                        "contractID":contractId,
	                        "contractType":contractType,
	                        "deviceName": deviceName,
	                        "type": type,
	                        "material": material,
	                        "unit": unit,
	                        "amount": amount,
	                        "price": price
	                    };
      			}
                    var url=window.rootPath+'/ui/contract/editOneReplacement';
                    var urlxy = window.rootPath + '/ui/contract/checkMoney?contractId=' + contractId + '&totalSum=' + totalSum;
                    jQuery.ajax({
                        url:encodeURI(url),
                        type:'post',
                        data:JSON.stringify(data),
                        dataType:'json',
                        contentType:'application/json;charset=utf-8',
                        success: function () {
                            jQuery('#editReplacementModal').modal('hide');
                            contractOtherData.contractId=jQuery('#contractId').val();
                            serverOtherTable.draw(false);
                            jQuery(".saveOtherBtn").attr("disabled", false);
                            jQuery.ajax({
                            	type : 'get',
                            	url : encodeURI(urlxy),
                            	dataType : 'json',
                            	contentType : 'application/json;charset=utf-8',
                            	success : function(data) {
                            		if(data==0){
                            			alert("合同金额与细目的总金额相同！");
                            		} else if(data==1){
                            			alert("合同金额小于细目的总金额！");
                            		} else if(data==2){
                            			alert("合同金额大于细目的总金额！");
                            		}
                            	}
                            });
                        }
                    });
    	});
    	
    	//EXCEL导入
        jQuery('.importOtherList').on("click",function()
        {
        	var contractId = jQuery('#contractId').val();
        	var type = '0';
        	if(contractId == ""){
            	if (confirm("当前合同还未保存，是否保存？")) {
            		saveContract('importOtherList');
            	}
            }else{
            	fileUpload(contractId, type);
            }
        });
        
        /**
    	 * 保存项目合同
    	 */
        var saveContract = function(state) {
        	var signedDate = jQuery('#signedDate').val();
         	var scheduleDate = jQuery('#scheduleDate').val();
         	var giveOutDate = jQuery('#giveOutDate').val();
     		var operatDate = jQuery('#operatDate').val();
     		if (signedDate==""||scheduleDate==""||giveOutDate==""||operatDate==""){
     			message("请将页面上所有日期信息完善，保存后还可进行编辑。");
     			return ;
     		}
      	    var isId=jQuery("#contractId").val();
      	    var contractcreateTime=jQuery("#createTime").val();
    	    var createTime=new Date(contractcreateTime).getTime();
      	    var supplierCode = jQuery('#supplierCode').val();
      		var demanderCode = jQuery('#demanderCode').val();
      		var contractType = jQuery('#contractType').val();
      		var totalSum = jQuery('#totalSum').val();
      		var stop = jQuery('#stop').val();
      		var freightCharge = jQuery('#freightCharge').val();
      		var projectName = jQuery('#projectName').val();
      	 	var payType = jQuery('#payType').val();
      	 	var guaranteePeriod = jQuery('#guaranteePeriod').val();
      	 	var breakDuty = jQuery('#breakDuty').val();
      	 	var customerId = jQuery("#customerId").val();
      		var orderUnit = jQuery('#orderUnit').val();
      	 	var orderDelegate = jQuery('#orderDelegate').val();
      		var orderPhone = jQuery('#orderPhone').val();
      		var industryInfo = jQuery('#industryInfo').val();
      		var orderAddress = jQuery('#orderAddress').val();
      		var orderZip = jQuery('#orderZip').val();
      		var orderArea = jQuery('#orderArea').val();
      		var invoiceBank = jQuery("#invoiceBank").val();
      		var bankAccount = jQuery("#bankAccount").val();
      		var taxNumber = jQuery("#taxNumber").val();
      		var invoiceAddress = jQuery("#invoiceAddress").val();
      		var postUnit = jQuery('#postUnit').val();
      	 	var postDelegate = jQuery('#postDelegate').val();
      		var postPhone = jQuery('#postPhone').val();
      		var postAddress = jQuery('#postAddress').val();
      		var postZip = jQuery('#postZip').val();
      		var dutyArea = jQuery('#dutyArea').val();
      		var dutyOfficer = jQuery('#dutyOfficer').val();
      		var southNorthArea = jQuery('#southNorthArea').val();
      		var belongArea = jQuery('#belongArea').val();
      		var checkKind = jQuery('#checkKind').val();
      		var productKind = jQuery('#productKind').val();
      		var signOfficer = jQuery('#signOfficer').val();
      		var repairOfficer = jQuery('#repairOfficer').val();
      		var quotationOfficer = jQuery('#quotationOfficer').val();
      		var operatDepartment = jQuery('#operatDepartment').val();
      		var operator = jQuery('#operator').val();
      		var memo = jQuery('#memo').val();
      		var state = jQuery('#state').val();
      		var cstate = jQuery('#cstate').val();
      		if(isId == ""){// 新增合同
	      		var d = {
	     				"user":{"id":$("#userId").val()},
	                	"supplierCode": supplierCode,
	                	"demanderCode": demanderCode,
	                	"contractType": contractType,
	                    "totalSum": totalSum,
	                    "signedDate": signedDate,
	                    "scheduleDate": scheduleDate,
	                    "giveOutDate": giveOutDate,
	                    "stop": stop,
	                    "freightCharge": freightCharge,
	                    "projectName": projectName,
	                    "payType": payType,
	                    "guaranteePeriod": guaranteePeriod,
	                    "breakDuty": breakDuty,
	                    "customerId": customerId,
	                    "orderUnit": orderUnit,
	                    "orderDelegate": orderDelegate,
	                    "orderPhone": orderPhone,
	                    "industryInfo": industryInfo,
	                    "orderAddress": orderAddress,
	                    "orderZip": orderZip,
	                    "orderArea": orderArea,
	                    "invoiceBank": invoiceBank,
      	                "bankAccount": bankAccount,
      	                "taxNumber": taxNumber,
      	                "invoiceAddress": invoiceAddress,
	                    "postUnit": postUnit,
	                    "postDelegate": postDelegate,
	                    "postPhone": postPhone,
	                    "postAddress": postAddress,
	                    "postZip": postZip,
	                    "dutyArea": dutyArea,
	                    "dutyOfficer": dutyOfficer,
	                    "southNorthArea": southNorthArea,
	                    "belongArea": belongArea,
	                    "checkKind": checkKind,
	                    "productKind": productKind,
	                    "signOfficer": signOfficer,
	                    "repairOfficer": repairOfficer,
	                    "quotationOfficer": quotationOfficer,
	                    "operatDepartment": operatDepartment,
	                    "operator": operator,
	                    "operatDate": operatDate,
	                    "memo": memo,
	                    "state": state,
	                    "cstate": cstate,
	            };
      		}else{
      			var d = {
      					"id": isId,
  	        			"createTime": createTime,
	                	"supplierCode": supplierCode,
	                	"demanderCode": demanderCode,
	                	"contractType": contractType,
	                    "totalSum": totalSum,
	                    "signedDate": signedDate,
	                    "scheduleDate": scheduleDate,
	                    "giveOutDate": giveOutDate,
	                    "stop": stop,
	                    "freightCharge": freightCharge,
	                    "projectName": projectName,
	                    "payType": payType,
	                    "guaranteePeriod": guaranteePeriod,
	                    "breakDuty": breakDuty,
	                    "customerId": customerId,
	                    "orderUnit": orderUnit,
	                    "orderDelegate": orderDelegate,
	                    "orderPhone": orderPhone,
	                    "industryInfo": industryInfo,
	                    "orderAddress": orderAddress,
	                    "orderZip": orderZip,
	                    "orderArea": orderArea,
	                    "invoiceBank": invoiceBank,
      	                "bankAccount": bankAccount,
      	                "taxNumber": taxNumber,
      	                "invoiceAddress": invoiceAddress,
	                    "postUnit": postUnit,
	                    "postDelegate": postDelegate,
	                    "postPhone": postPhone,
	                    "postAddress": postAddress,
	                    "postZip": postZip,
	                    "dutyArea": dutyArea,
	                    "dutyOfficer": dutyOfficer,
	                    "southNorthArea": southNorthArea,
	                    "belongArea": belongArea,
	                    "checkKind": checkKind,
	                    "productKind": productKind,
	                    "signOfficer": signOfficer,
	                    "repairOfficer": repairOfficer,
	                    "quotationOfficer": quotationOfficer,
	                    "operatDepartment": operatDepartment,
	                    "operator": operator,
	                    "operatDate": operatDate,
	                    "memo": memo,
	                    "state": state,
	                    "cstate": cstate,
	            };
      		}
      		jQuery(".addOtherBtn").attr("disabled", true);
      		jQuery(".importOtherList").attr("disabled", true);
      		jQuery(".addPumpBtn").attr("disabled", true);
      		jQuery(".importPumpList").attr("disabled", true);
      		var id=isId;
      		if (id==null||id==''){
      			id = 'null';
      		}
      		if (cstate=="已完成"){
      			$.springLemonDialog({
  					content : '该合同已经生产商品计划，不能保存！',// 确认文本
  					clickButton : function(sender, modal, index) {// 按钮事件处理
  						$(this).closeDialog(modal);
  					}
      			});
  			}
      		if(cstate=="已排产"){
      			alert("保存合同后将修改排产相关信息。");
      		}
      		if (supplierCode!=''){// 验证供方合同号是否已存在
      			var urlValid=window.rootPath+"/ui/contract/validSupplierCode/"+id+"/"+supplierCode;
      	    	jQuery.ajax({
      	            url:encodeURI(urlValid),
      	            cache:false,
      	            type :"get",
      	            dataType:"json",
      	            contentType:"application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
      	            success:function(data){
      	            	if(data.codeState==1){
      	            		$.springLemonDialog({
      		      		         content: '供方合同号已存在，请修改！',// 确认文本
      		      		         clickButton: function (sender, modal, index) {// 按钮事件处理
      		      		             $(this).closeDialog(modal);
      		      		         }
      		            		});
      	            		jQuery(".addOtherBtn").attr("disabled", false);
      	            		jQuery(".importOtherList").attr("disabled", false);
      	            		jQuery(".addPumpBtn").attr("disabled", false);
      	            		jQuery(".importPumpList").attr("disabled", false);
      	            		return;
      	            	}
      	                    var url = window.rootPath + "/ui/contract/saveContract";
      	                    jQuery.ajax({
      	                        type: 'post',
      	                        url: url,
      	                        data: JSON.stringify(d),
      	                        dataType: 'json',
      	                        contentType: 'application/json;charset=utf-8',
      	                        success: function (data) {
      	                        	var contractId = data.contractId;
      	                        	var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
      	                        	jQuery("#createTime").val(time);
      	                        	jQuery("#contractId").val(contractId);
      	                        	jQuery(".addOtherBtn").attr("disabled", false);
      	      	            		jQuery(".importOtherList").attr("disabled", false);
      	      	            		jQuery(".addPumpBtn").attr("disabled", false);
      	      	            		jQuery(".importPumpList").attr("disabled", false);
      	                        	if (state=="addOtherBtn"){
      	                        		showReplacementModal();
      	                        	}else if(state=="importOtherList"){
      	                        		var type = '0';
      	                        		fileUpload(contractId, type);
      	                        	}
      	                        }
      	                    });
      	            }
      	    	});
      		}else{
      	            var url = window.rootPath + "/ui/contract/saveContract";
      	            jQuery.ajax({
      	                type: 'post',
      	                url: url,
      	                data: JSON.stringify(d),
      	                dataType: 'json',
      	                contentType: 'application/json;charset=utf-8',
      	                success: function (data) {
      	                	var contractId = data.contractId;
      	                	var time=moment(data.createTime).format("YYYY-MM-DD HH:mm:ss")
	                        jQuery("#createTime").val(time);
      	                	jQuery("#contractId").val(contractId);
      	                	jQuery(".addOtherBtn").attr("disabled", false);
	                    	jQuery(".importOtherList").attr("disabled", false);
	                    	jQuery(".addPumpBtn").attr("disabled", false);
	                     	jQuery(".importPumpList").attr("disabled", false);
	                        if (state=="addOtherBtn"){
	                        	showReplacementModal();
	                       	}else if(state=="importOtherList"){
  	                        	var type = '0';
  	                       		fileUpload(contractId, type);
  	                       	}
      	                }
      	            });
      		}
      	};
      	
      	/**
      	 * 添加其他时初始化弹窗
      	 */
        var showReplacementModal = function() {
        	jQuery('#replacementId').val('');
        	jQuery('#replacementcreateTime').val('');
    		jQuery('#deviceName').val('');
    		jQuery('#type').val('');
    		jQuery('#material').val('');
    		jQuery('#unit').val('');
    		jQuery('#amount').val('');
    		jQuery('#price').val('');
    		jQuery('#editReplacementModal').modal('show');
        }
    	
    	/**
    	 * 文件上传插件
    	 */
    	var fileUpload = function(contractId, type) {
    		var root = window.rootPath;
    		WebFilesUploader(
    				{
    					_webuploader : {
    						server : root + '/ui/contract/import/' + contractId +'/'+ type,
    						swf : root
    								+ '/resources/poweradminjs/webupload/webfilesuploader/Uploader.swf',
    						chunked:false		
    					}
    				
    				}, function(jsons) {  		
    					contractOtherData.contractId=jQuery('#contractId').val();
    					serverOtherTable.draw(true);
    				});
           
    	
    	};
    	
    	//列表中的全选
        $("#checkAllOther").click(function(){
        	var check = $(this).prop("checked");
            $(".checkchildOther").prop("checked", check);
    	});
    	
    });
})();